//index.js
//获取应用实例
const app = getApp()
/**
 * 支付 
 * 
 * -> 请求接口，提交小程序id和密钥，获取openid 
 * -> 生成订单，返回时间戳、签名等
 * -> 调用支付，wx.requestPayment，成功后wx.navigateBack 
 * 
 */
Page({
  data: {
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    currentData:[
        {
            id: 1,
            val:'',
            isActive: true,
        },
        {
            id: 2,
            val:'',
            isActive: false
        },
        {
            id: 3,
            val:'',
            isActive: false
        },
        {
            id: 4,
            val:'',
            isActive: false
        },
        {
            id: 5,
            val:'',
            isActive: false
        },
        {
            id: 6,
            val:'',
            isActive: false
        },
        {
            id: 7,
            val:'',
            isActive: false
        }
    ],
    location: [
        '粤','京','沪','津','浙','苏','湘',
        '赣','鄂','豫','皖','陕','甘','宁',
        '云','贵','川','渝','黑','吉','辽',
        '晋','冀','鲁','闽','琼','桂','蒙',
        '青','藏','新'
    ],
    number: [1,2,3,4,5,6,7,8,9,0],
    alphabet: [
        'A','B','C','D','E','F','G',
        'H','J','K','L','M','N','O',
        'P','Q','R','S','T','U','V',
        'W','X','Y','Z'
    ],
    special: ['港','澳','学','领'],
    payInfo: {
        // amount: 999,
        // number: '粤A***35',
        // locate: '中山六院',
        // time: '06-29 13:33:33',
        // duration: '0小时20分钟12秒'
    },
    historyData: [      // 历史记录
        // {
        //     time: '近期',
        //     number: '粤A77J35'
        // }
    ],
    checkDisabled: false,   //  是否允许查询
    currSelect: {},      // 当前选中的数字
    canShowKeyboard: 0,     // 隐藏键盘:0, 显示省市:1, 显示字母数字:2
    // 输入限制相关
    canChooseNumAndText: true, 
    canChooseO: true,       // 是否允许选择O
    canChooseSpecial: true, 
    // 支付相关
    canShowPayInfo: false,  // 是否显示支付弹窗
    payStatus: 2,         // 隐藏所有:0, 显示支付:1, 显示记录:2，显示暂无订单:3
    openId: '',     // 用于调用微信支付
    canShowTips: false,
    // tipsText: '当前线上支付为测试版，不支持优惠（2.5/小时）结算、不设找零，如遇问题，请联系19928321397', // 原六院提示语
    tipsText: '',
    discount: '',
    orderTips: '',
    paySuccess: false
  },
  choose(e){
    this.setData({
        currentData: this.data.currentData.map(v => {
            if(v.id == this.data.currSelect.id){
                v.val = e.target.dataset.item.val.toString()
            }
            v.id == this.data.currSelect.id + 1 ? v.isActive = true : v.isActive = false
            return v
        }),
        currSelect: this.data.currentData.find(v => v.id == this.data.currSelect.id + 1),
        canShowKeyboard: this.data.currSelect.id + 1 == 1 ? 1 : 2,
        canChooseNumAndText: this.data.currSelect.id + 1 == 2 ? false : true,
        canChooseO: this.data.currSelect.id + 1 >= 3 ? false : true,
        canChooseSpecial: this.data.currSelect.id == this.data.currentData.length - 1 ? true : false
    }, () => {
        if(this.data.currSelect == undefined){
            this.setData({
                canShowKeyboard: 0
            })
        }
        this.checkOption()
    })
    console.log(this.data.currentData)
  },
  showKeyboard(e){
    console.log(e)
    console.log(this.data.currentData.length)
    this.setData({
        currentData: this.data.currentData.map(v => ({...v, isActive: v.id == e.target.dataset.item.id ? true : false})),
        currSelect: e.target.dataset.item,
        canShowKeyboard:  e.target.dataset.item.id == 1 ? 1 : 2,
        canShowPayInfo: false
    }, () => {
        this.setData({
            canChooseNumAndText: this.data.currSelect.id == 2 ? false : true,
            canChooseO: this.data.currSelect.id + 1 >= 3 ? false : true,
            canChooseSpecial: this.data.currSelect.id == this.data.currentData.length ? true : false
        })
    })
  },
  changeTotal(){
    // 判断最后一位是否为“港澳学领”，是，则需要空2位,当前高亮倒数第二位。若否，正常空位，并弹出keyboard
    // 切换为8位
    if(this.data.currentData.length == 7){
        this.data.currentData.push({
            id: 8,
            val: '',
            isActive: false
        })
        
        let flag = false
        this.data.special.forEach(v => {
            if(v.val == this.data.currentData[6].val){
                flag = true
            }
        })

        if(!flag){  // 最后一位不是“港澳学领”
            this.setData({
                currentData: this.data.currentData.map(v => {
                    v.id == 8 ? v.isActive = true : v.isActive = false
                    return v
                }), // bug:第七位为空的情况下，点击切换到8位，应该继续高亮第七位。当第七位有内容时，切换才高亮8位
                currSelect: this.data.currentData[7],
                canShowKeyboard: 2,
                canChooseO: false,
                canChooseSpecial: true
            })
        }else{  // 最后一位是“港澳学领”
            this.setData({
                currentData: this.data.currentData.map(v => {
                    if(v.id == 7 || v.id == 8) {
                        v.val = ''
                    }
                    v.id == 7 ? v.isActive = true : v.isActive = false
                    return v
                }),
                currSelect: this.data.currentData[6],
                canShowKeyboard: 2,
                canChooseO: false,
                canChooseSpecial: false
            })
        }
    }else{
        this.data.currentData.pop()
        this.setData({
            currentData: this.data.currentData.map(v => ({ ...v, isActive: v.id == 7 ? true : false})), // 第7位高亮
            currSelect: this.data.currentData[6],
            canShowKeyboard: 2,
            canChooseO: false,
            canChooseSpecial: true
        })
    }
    this.setData({
        currentData: this.data.currentData
    }, () => {
        this.checkOption()
    })
  },
  payMoney(){
    let str = ''
    this.data.currentData.forEach(v => {
        str += v.val
    })

    wx.showModal({
        title: '提示',
        content: '确定支付？',
        success: res => {
          if(res.confirm) {
            console.log('用户点击确定')

            wx.request({
                url: 'https://tktcpay.eai9.com/pay/payfee',
                method: 'GET',
                data:{
                    oid: app.globalData.openId,
                    license: str,
                    dis: this.data.discount
                },
                success: res => {
                    console.log(res.data)
                    // 如果不为空
                    
                    console.log('调起支付')
                    wx.requestPayment({
                        'appId': res.data.appId, 
                        'timeStamp': res.data.timeStamp.toString(),
                        'nonceStr': res.data.nonceStr,
                        'package': res.data.package,
                        'signType': 'MD5',
                        'paySign': res.data.paySign,
                        'openId': app.globalData.openId,
                        'success':res => {
                            console.log(res)

                            this.setData({
                                canShowTips: false,
                                paySuccess: true,
                                payInfo: {},  // 先清空价格
                                payStatus: 0,    // 隐藏价格表
                                canShowKeyboard: 0  // 隐藏键盘
                            }, () => {
                                setTimeout(() => {
                                    this.setData({
                                        paySuccess: false
                                    })
                                }, 2000)
                                this.saveInLocal(str)
                            })
                        },
                        'fail':res => {
                            console.log(res)
                        }
                    })
                },
                fail: e => {
                    wx.showModal({
                        title: '错误',
                        content: `${e.errCode}，${e.errMsg}`,
                    })
                }
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
            this.setData({
                payInfo: {},  // 先清空价格
                payStatus: 0,    // 隐藏价格表
                canShowKeyboard: 0  // 隐藏键盘
            }, () => {
                this.saveInLocal(str)
            })
          }
        }
    })
  },
  saveInLocal(str){
    let arr = []
    wx.getStorage({
        key: 'history',
        success: res => {
            console.log(res.data)
            arr = res.data
            
            // 禁止重复存同车牌
            let isSaved = 0
            arr.forEach(v => {
                if(v == str) isSaved++
            })

            if(isSaved > 0) {
                this.setData({
                    payStatus: 2
                })
                return;
            }
            
            arr.unshift(str)
            
            wx.setStorage({
                key: 'history',
                data: arr,
                success: () => {
                    wx.getStorage({
                        key: 'history',
                        success: res => {
                            console.log(res.data)

                            let tmp = res.data.map(v => {
                                return {
                                    time: '近期',
                                    number: v
                                }
                            })

                            this.setData({
                                payStatus: 2,
                                historyData: tmp
                            })
                        } 
                    })
                    
                }
            })
        }
    })
  },
  changeNumber(e){
    let newArr = e.currentTarget.dataset.number.split('')
    this.setData({
        currentData: this.data.currentData.map((v, idx) => {
            return {
                ...v,
                val: newArr[idx]
            }
        })
    }, () => {
        this.searchNum()
    })
  },
  searchNum(){
    this.setData({
        canShowKeyboard: 0,
        canShowPayInfo: this.data.payStatus == 1 ? true : false,
    }, () => {
        let str = ''
        this.data.currentData.forEach(v => {
            str += v.val
        })

        wx.request({
            url: 'https://tktcpay.eai9.com/license',
            method: 'GET',
            data: { license: str, dis: this.data.discount },
            success: res => {
                if(res.data.success){
                    let str = ''
                    if(res.data.locate.indexOf('中山六院') != -1){
                        str = '当前为线上支付，不支持优惠，如是就诊病人请前往1号楼1楼登记领取优惠码'
                    }else{
                        str = ''
                    }
                    res.data.amount = res.data.amount / 100
                    res.data.amountdis = res.data.amountdis / 100
                    this.setData({
                        payStatus: 1,
                        payInfo: res.data,
                        tipsText: str,
                        canShowTips: res.data.locate.indexOf('中山六院') != -1 ? true : false
                    })
                }else{
                    this.setData({
                        payStatus: 3
                    })
                }

                wx.setStorage({
                    key: 'current_car_number',
                    data: str
                })

                if(res.data.uplr != {}){
                    switch(res.data.uplr.status){
                        case '20': res.data.uplr.type = '忽略'; break;
                        case '21': res.data.uplr.type = '收费放行'; break;
                        case '22': res.data.uplr.type = '免费放行'; break;
                        case '23': res.data.uplr.type = '系统免费放行'; break;
                        case '24': res.data.uplr.type = '系统VIP放行'; break;
                        case '26': res.data.uplr.type = '折扣'; break;
                        case '27': res.data.uplr.type = '异常（修改金额）'; break;
                        case '28': res.data.uplr.type = '微信'; break;
                        case '29': res.data.uplr.type = '支付宝'; break;
                    }
                    this.setData({
                        orderTips: res.data.uplr
                    })
                }
            }
        })
    })
  },
  removeNum(){
    console.log(this.data.currSelect)
    this.setData({
        currentData: this.data.currentData.map(v => {
            if(v.id == this.data.currSelect.id){
                v.val = '';
                v.isActive = false;
            }
            if(v.id == this.data.currSelect.id - 1){
                v.isActive = true;
            }
            return v 
        }),
        currSelect: this.data.currentData.find(v => v.id == this.data.currSelect.id - 1),
        canShowKeyboard: this.data.currSelect.id - 1 == 1 ? 1 : 2,
        canChooseNumAndText: this.data.currSelect.id - 1 == 2 ? false : true,
        canChooseO: this.data.currSelect.id - 1 >= 3 ? false : true,
        canChooseSpecial: this.data.currSelect.id == this.data.currentData.length + 1 ? true : false,
    }, () => {
        this.checkOption()
    })
  },
  hideKeyboard(){
    this.setData({
        canShowKeyboard: 0,
        payStatus: 0,
        currentData: this.data.currentData.map(v => ({...v, isActive: false})),
        currSelect: {}
    })
  },
  checkOption(){
    let flag = false
    this.data.currentData.forEach(v => {
        if(v.val == '') flag = true
    })
    this.setData({
        checkDisabled: flag,
        payStatus: 0
    })
  },
  removeHistory(e){
    /*
        删除历史记录
        1.先删除historyData里的这个车牌
        2.wx.getStorage()获取本地缓存，将对应的删去
    */
    this.setData({
        historyData: this.data.historyData.filter(v => v.number != e.currentTarget.dataset.number)
    }, () => {
        // 变回纯字符串的数组，再保存到本地缓存
        let newArr = []
        this.data.historyData.forEach(v => {
            newArr.push(v.number)
        })

        wx.setStorage({
            key: 'history',
            data: newArr,
            success: res => {
                console.log('删除成功')
                wx.getStorage({
                    key: 'history',
                    success: res => {
                        console.log(res.data)
                    }
                })
            }
        })
    })
  },
  onLoad(options) {
    console.log(options)
    if(options.q != undefined){
        let scan_url = decodeURIComponent(options.q)
        if(scan_url.indexOf('dis=') != -1){
            let code = scan_url.split('dis=')[1]
            this.setData({
                discount: code
            })
        }
    }

    wx.setStorage({
        key: 'history',
        data: []
    })

    wx.getStorage({
        key: 'current_car_number',
        success: res => {
            if(res.errMsg == 'getStorage:ok'){
                let arr = [], carNumber = res.data.split('');
                this.data.currentData = []
                for(let i = 0; i < 7; i++){
                    arr.push({
                        id: i + 1,
                        val: carNumber[i],
                        isActive: false,
                    })
                }
                this.setData({
                    currentData: arr
                })
            }
        }
    })

    this.setData({
        location: this.data.location.map(v => {
            return {
                val: v,
                isActive: false
            }
        }),
        number: this.data.number.map(v => {
            return {
                val: v,
                isActive: false
            }
        }),
        alphabet: this.data.alphabet.map(v => {
            return {
                val: v,
                isActive: false
            }
        }),
        special: this.data.special.map(v => {
            return {
                val: v,
                isActive: false
            }
        }),
        currSelect: this.data.currentData[0],
    }, () => {
        console.log(this.data.dataList)
    })

    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse){
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
  },
  onShow(){
    if(this.data.currentData[0].isActive){
        this.setData({
            canShowKeyboard: 1
        })
    }
  },
  getUserInfo(e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  }
})
